// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  
  if (!openid) {
    return {
      success: false,
      message: '请先登录'
    }
  }
  
  try {
    const { articleId } = event
    
    if (!articleId) {
      return {
        success: false,
        message: '文章ID不能为空'
      }
    }
    
    // 检查文章是否存在
    const articleRes = await db.collection('articles').doc(articleId).get()
    
    if (!articleRes || !articleRes.data) {
      return {
        success: false,
        message: '文章不存在或已删除'
      }
    }
    
    // 查询是否已收藏
    const collectionRes = await db.collection('collections')
      .where({
        _openid: openid,
        articleId
      })
      .get()
    
    const isCollected = collectionRes.data.length > 0
    
    // 开始事务
    const transaction = await db.startTransaction()
    
    try {
      if (isCollected) {
        // 取消收藏
        await transaction.collection('collections')
          .where({
            _openid: openid,
            articleId
          })
          .remove()
        
        // 减少文章收藏数
        await transaction.collection('articles')
          .doc(articleId)
          .update({
            data: {
              collectionCount: _.inc(-1)
            }
          })
      } else {
        // 添加收藏
        await transaction.collection('collections')
          .add({
            data: {
              _openid: openid,
              articleId,
              createTime: db.serverDate(),
              article: articleRes.data
            }
          })
        
        // 增加文章收藏数
        await transaction.collection('articles')
          .doc(articleId)
          .update({
            data: {
              collectionCount: _.inc(1)
            }
          })
      }
      
      // 提交事务
      await transaction.commit()
      
      return {
        success: true,
        data: {
          isCollected: !isCollected
        }
      }
    } catch (err) {
      // 回滚事务
      await transaction.rollback()
      throw err
    }
  } catch (err) {
    console.error('收藏操作失败', err)
    return {
      success: false,
      message: '操作失败，请重试',
      error: err
    }
  }
}